<template>
  <div class="app-container">
    <div class="div-table">
      <div class="search-form" style="margin-bottom:15px;">
        <el-input
          v-model="searchForm.name"
          size="small"
          clearable
          placeholder="脚本名"
          style="width:200px;"
        />
        <el-button type="primary" size="small" @click="() => fetchData()">查询</el-button>
        <el-button type="primary" size="small" @click="() => reset()">重置</el-button>
        <el-button type="primary" size="small" @click="() => addOrUpdate()">新增</el-button>
      </div>
      <el-table
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        @sort-change="sortTable"
      >
        <el-table-column label="序号" width="50">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="名称" prop="name" sortable>
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="语言" prop="scriptLang" sortable>
          <template slot-scope="scope">{{ scope.row.scriptLang }}</template>
        </el-table-column>
        <el-table-column label="超时时间(秒)" prop="timeout" sortable>
          <template slot-scope="scope">{{ scope.row.timeout }}</template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" sortable>
          <template slot-scope="scope">{{ scope.row.remark }}</template>
        </el-table-column>
        <el-table-column label="创建时间" prop="updateTime" sortable>
          <template slot-scope="scope">
            <i class="el-icon-time" />
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createName" sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.createName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template slot-scope="scope">
            <el-button size="small" type="success" @click="() => selectHost(scope.row)">执行</el-button>
            <el-button size="small" type="primary" @click="() => addOrUpdate(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="() => del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <pagination :pagination="pagination" />
      </div>
    </div>

    <el-dialog :title="activeTitle" :visible.sync="dialogFormVisible">
      <el-form ref="ruleForm" :model="form" :rules="formrules">
        <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" clearable autocomplete="off" />
        </el-form-item>
        <el-form-item label="语言" :label-width="formLabelWidth" prop="scriptLang">
          <el-select
            v-model="form.scriptLang"
            size="small"
            clearable
            filterable
            placeholder="请选择脚本语言"
          >
            <el-option
              v-for="item in scriptLangMaps"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" :label-width="formLabelWidth" prop="context">
          <el-input
            v-model="form.context"
            class="textarea"
            type="textarea"
            :autosize="{ minRows: 10, maxRows: 30}"
            placeholder="请输入脚本内容"
          />
        </el-form-item>
        <el-form-item label="超时时间(秒)" :label-width="formLabelWidth" prop="timeout">
          <el-input v-model="form.timeout" clearable autocomplete="off" />
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
          <el-input v-model="form.remark" clearable autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="runScriptTitle" :visible.sync="dialogHostTableVisible">
      <el-table
        ref="multipleHostTable"
        :data="hostList"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        @sort-change="sortTable"
        @selection-change="handleHostSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column label="主机名" prop="hostname" sortable>
          <template slot-scope="scope">{{ scope.row.hostname }}</template>
        </el-table-column>
        <el-table-column label="IP地址" prop="ipaddr" sortable>
          <template slot-scope="scope">{{ scope.row.ipaddr }}</template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancelHostSelection()">取 消</el-button>
        <el-button type="primary" size="small" @click="() => runScript()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination/index'
import { getList, getDetail, save, del } from '@/api/systemapi/script'
import { run } from '@/api/systemapi/job'
import { getAll as getUserList } from '@/api/systemapi/user'
import { getAll as getHostList } from '@/api/systemapi/host'
import { pageParams } from '@/settings'
import { sleep } from '@/utils/time'

export default {
  components: {
    pagination: Pagination
  },
  filters: {
    statusTypeFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      scriptLangMaps: [
        { id: 1, name: 'shell' },
        { id: 2, name: 'python' },
        { id: 3, name: 'go' }
      ],
      userList: [], // 用户列表
      list: null, // 脚本列表
      listLoading: true,
      searchForm: {
        sidx: '', // 排序字段
        sord: '', // 排序方向
        name: '',
        rows: '10',
        page: '1'
      },
      activeTitle: '新增脚本', // 新增编辑菜单模态框标题
      dialogFormVisible: false, // 模态框
      formLabelWidth: '100px',
      // 新增&编辑 表单
      form: {
        name: '',
        scriptLang: '',
        context: '',
        timeout: 300,
        remark: ''
      },
      formrules: {
        name: [
          { required: true, message: '名称', trigger: 'blur' }
        ],
        scriptLang: [
          { required: true, message: '语言', trigger: 'blur' }
        ],
        context: [
          { required: true, message: '内容', trigger: 'change' }
        ],
        timeout: [
          { required: true, message: '超时时间(秒)', trigger: 'change' }
        ],
        remark: [
          { required: false, message: '备注', trigger: 'blur' }
        ]
      },
      // 当前选择的脚本ID
      currentScriptId: '',
      // 分页
      pagination: pageParams,

      // 主机相关
      runScriptTitle: '执行脚本',
      dialogHostTableVisible: false, // 主机选择模态框
      hostList: [],
      hostSelection: []
      // runScriptForm: {
      //     id: '',
      //     hostList: []
      // }
    }
  },
  watch: {
    // 分页查询
    'pagination.currentPage': function() {
      this.searchForm.page = this.pagination.currentPage
      this.fetchData()
    },
    'pagination.pageSize': function() {
      this.searchForm.rows = this.pagination.pageSize
      this.searchForm.page = 1
      this.fetchData()
    },
    // 分页查询
    'hostPagination.currentPage': function() {
      this.searchForm.page = this.pagination.currentPage
      this.fetchHostData()
    },
    'hostPagination.pageSize': function() {
      this.searchForm.rows = this.pagination.pageSize
      this.searchForm.page = 1
      this.fetchHostData()
    }
  },
  // 页面初始化时执行
  created() {
    // 脚本列表
    this.fetchData()
    this.fetchUserData()
    this.fetchHostData()
  },
  methods: {
    // 重置搜索，刷新列表
    reset() {
      this.searchForm = {
        sidx: '', // 排序字段
        sord: '', // 排序方向
        name: '',
        rows: '10',
        page: '1'
      }
      this.currentArea = null
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      getList({ ...this.searchForm }).then(response => {
        this.list = response.data.rows
        this.pagination.total = response.data.records
        this.listLoading = false
      })
    },
    fetchUserData() {
      getUserList({}).then(response => {
        this.userList = response.data
      })
    },
    fetchHostData() {
      getHostList({}).then(response => {
        this.hostList = response.data
      })
    },
    sortTable(column) {
      // 获取字段名称和排序类型
      var fieldName = column.prop
      var sortingType = column.order

      const sortTypeMap = {
        '': '',
        ascending: 'asc',
        descending: 'desc'
      }

      this.searchForm.sidx = fieldName
      this.searchForm.sord = sortTypeMap[sortingType]

      this.fetchData()
    },
    // 删除
    del(data) {
      this.$confirm('是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del(data.id).then(response => {
            if (response.code === 0) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.dialogFormVisible = false
              this.fetchData()
            } else {
              this.$message({
                message: response.msg,
                type: 'error'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 新增
    addOrUpdate(data) {
      this.resetFileds()
      this.form = {
        name: '',
        scriptLang: '',
        context: '',
        timeout: 300,
        remark: ''
      }
      this.dialogFormVisible = true
      this.activeTitle = '新增脚本'
      if (data) {
        this.activeTitle = '编辑脚本'
        getDetail(data.id).then(response => {
          this.form = response.data
        })
      }
    },
    // 保存
    save() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          save({ ...this.form }).then(response => {
            if (response.code === 0) {
              this.$message({
                message: '新增脚本成功',
                type: 'success'
              })
              this.dialogFormVisible = false
              this.fetchData()
            } else {
              this.$message({
                message: response.msg,
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    runScript() {
      if (this.hostSelection.length === 0) {
        this.$alert('请选择至少一个主机')
      } else {
        var data = {
          id: this.currentScriptId,
          hostList: this.hostSelection
        }
        run(data).then(response => {
          if (response.code === 0) {
            this.$message({
              message: '创建任务成功',
              type: 'success'
            })
            this.dialogFormVisible = false
            sleep(1000)
            // 跳转到详情页
            this.$router.push('/system/job/detail?jobId=' + response.data.jobId)
          } else {
            this.$message({
              message: response.msg,
              type: 'error'
            })
          }
        })
      }
    },
    resetFileds() {
      // 重置校验
      if (this.$refs['ruleForm']) {
        this.$refs['ruleForm'].resetFields()
      }
    },
    handleHostSelectionChange(val) {
      this.hostSelection = val
    },
    cancelHostSelection(rows) {
      this.dialogHostTableVisible = false
      this.$refs.multipleHostTable.clearSelection()
    },
    selectHost(data) {
      this.dialogHostTableVisible = true
      this.currentScriptId = data.id
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  display: flex;
  width: 100%;
  .div-tree {
    width: 300px;
  }
  .div-table {
    flex: 1;
  }
}

</style>
